package com.potenza.training.reply.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.potenza.training.reply.config.FastDFSClient;
import com.potenza.training.reply.config.WirteExcelUtil;
import com.potenza.training.reply.dao.EsDao;
import com.potenza.training.reply.entity.*;
import com.potenza.training.reply.feign.SubjectFegin;
import com.potenza.training.reply.service.KeyWordService;
import com.potenza.training.reply.service.SubjectService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFDataValidationHelper;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.*;


/**
 * 机构创建题目表
 *
 * @author lihonggang
 * @email lihonggang@gmail.com
 * @date 2021-07-22 15:57:42
 */
@RestController
@RequestMapping("reply/subject")
public class SubjectController {
    @Autowired
    private SubjectService subjectService;
    @Autowired
    private KeyWordService keyWordService;
    @Autowired
    private FastDFSClient fastDFSClient;
    @Autowired
    private EsDao esDao;
    @Autowired
    private SubjectFegin subjectFegin;
    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("reply:subject:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = subjectService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("reply:subject:info")
    public R info(@PathVariable("id") Long id){
		SubjectEntity subject = subjectService.getById(id);
		//分词信息表
      List<KeyWordEntity> keyWordEntityList= keyWordService.findbysubjectid(id);

        return R.ok().put("subject", subject).put("keyWordEntityList",keyWordEntityList);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("reply:subject:save")
    public R save(@RequestBody SubjectDTO subjectDTO){

        return subjectService.saveIkAndSubject(subjectDTO);
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("reply:subject:update")
    public R update(@RequestBody SubjectDTO subjectDTO){

        SubjectEntity subject= new SubjectEntity();
        subject.setId(subjectDTO.getId());
        subject.setTimeLimit(subjectDTO.getTimeLimit());
        subject.setSubjectType(subjectDTO.getSubjectType());
        subject.setSubjectDifficlty(subjectDTO.getSubjectDifficlty());
        subject.setSubiectDesc(subjectDTO.getSubiectDesc());
        subject.setTitleName(subjectDTO.getTitleName());
        subject.setEndData(new Date());
        subject.setStandardAnswer(subjectDTO.getStandardAnswer());//标准答案
		subjectService.updateById(subject);

        String keyword1 = "";
        String groups1="";
        Integer i=0;
        List<KeyWordEntity> keyWordEntityList = subjectDTO.getKeyWordEntityList();
        for (KeyWordEntity keyWordEntity : keyWordEntityList) {

            List<Cs> cs = JSON.parseArray(keyWordEntity.getKeyWordName(), Cs.class);
            for (Cs c : cs) {
                keyword1 += c.getKeyWordName() + ",";
                i++;
            }
            groups1+=i+":"+keyWordEntity.getGroups()+",";
            keyWordService.updateById(keyWordEntity);

        }

        EsSubjectEntity esSubjectEntity = new EsSubjectEntity();
        esSubjectEntity.setId(subjectDTO.getId());
        esSubjectEntity.setSubjectType(subject.getSubjectType());
        esSubjectEntity.setSubjectDifficlty(subject.getSubjectDifficlty());
        esSubjectEntity.setTitleName(subject.getTitleName());
        esSubjectEntity.setStandardAnswer(subject.getStandardAnswer());
        esSubjectEntity.setTimeLimit(subject.getTimeLimit());
        esSubjectEntity.setSubiectDesc(subject.getSubiectDesc());
        esSubjectEntity.setIsStart(1);
        esSubjectEntity.setBeginData(subject.getBeginData());
        esSubjectEntity.setEndData(subject.getEndData());
        esSubjectEntity.setTypeId(subject.getTypeId());
        esSubjectEntity.setDifficltyId(subject.getDifficltyId());
        esSubjectEntity.setKeyWordName(keyword1);
        esSubjectEntity.setGroups(groups1);
        esDao.updateById(esSubjectEntity);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("reply:subject:delete")
    public R delete(@RequestBody Long[] ids){
		subjectService.removeByIds(Arrays.asList(ids));
        for (Long id : ids) {
            keyWordService.deletekeyWord(id);
        }
        return R.ok();
    }
    /**
     * 分页
     */
    @RequestMapping("/findAll/{pageNum}/{pageSize}")
    @RequiresPermissions("reply:replygroup:findAll")
    public R listAll(@RequestBody Map map,@PathVariable Integer pageNum,@PathVariable Integer pageSize){
        Page<SubjectEntity> page = subjectService.findAll(map,pageNum,pageSize);

        return R.ok().put("page", page);
    }

    /**
     * 随机
     */
    @RequestMapping("/immediately/{id}")
    @RequiresPermissions("reply:replygroup:immediately")
    public R immediately(@PathVariable Integer id){
        subjectService.immediately(id);

        return R.ok();
    }

    //fast文件上传
    @PostMapping("upload")
    public R imageUpload(MultipartFile file) throws Exception {
        System.out.println("上传的文件："+file);
        String name = file.toString();
        String path = "D:\\题目文件\\Excel\\";
        File temporaryFile = new File(path);
        if(!temporaryFile.exists()){
            temporaryFile.mkdirs();
        }
        File uploadExcel = new File(path + name);
        file.transferTo(uploadExcel);
        FileInputStream fileInputStream = new FileInputStream(uploadExcel.getPath());
        return subjectService.saveSubject(fileInputStream);
    }

    //获取题目模板
    @GetMapping("getModel")
    public R getModel(){
        WirteExcelUtil wirteExcelUtil = new WirteExcelUtil();
        //创建一个新的excel
        XSSFWorkbook model = new XSSFWorkbook();
        //创建用户需要填写的部分
        XSSFSheet subjectSheet = model.createSheet("题目模板");
        //创建行
        Row row0 = subjectSheet.createRow(0);
        //列表行内需要的数据
        row0.createCell(0).setCellValue("题目类型");
        row0.createCell(1).setCellValue("题目类型");
        row0.createCell(2).setCellValue("题目类型");
        row0.createCell(3).setCellValue("题目名称");
        row0.createCell(4).setCellValue("标准答案");
        row0.createCell(5).setCellValue("题目难度");
        row0.createCell(6).setCellValue("答题时间");
        row0.createCell(7).setCellValue("题目描述");
        //用来存放所有有子目录的父目录
        List<String> typeFatherArr = new ArrayList<>();
        //获取数据库内的一级菜单
        List<SubjectTypeEntity> one = subjectFegin.findTypeByPid(0);
        String[] typeOneArr = new String[one.size()];
        //将一级目录加入到string数组
        for (int i = 0 ;i<one.size();i++){
            typeOneArr[i] = one.get(i).getTypeName();
        }
        List<SubjectTypeEntity> twe = new ArrayList<>();
        for (SubjectTypeEntity subjectTypeEntity : one) {
            twe.addAll(subjectFegin.findTypeByPid(Integer.parseInt(subjectTypeEntity.getId()+"")));
        }
        List<SubjectTypeEntity> three = new ArrayList<>();
        for (SubjectTypeEntity subjectTypeEntity : twe) {
            three.addAll(subjectFegin.findTypeByPid(Integer.parseInt(subjectTypeEntity.getId()+"")));
        }
        //获取数据库内的难度一级菜单
        List<SubjectDifficultyEntity> difficulty = subjectFegin.findDifficultyByPid(0);
        String[] difficultyArr = new String[difficulty.size()];
        //将一级目录加入到string数组
        for (int i = 0 ;i<difficulty.size();i++){
            difficultyArr[i] = difficulty.get(i).getDifficultyName();
        }
        //创建string数组的集合
        List<String[]> stringList = new ArrayList<String[]>();
        //将二级目录加入到对应的集合
        for (int i=0;i<one.size();i++){
            int k = 0;
            List<String> list = new ArrayList<>();
            for (int j=0;j<twe.size();j++){
                if(twe.get(j).getPid()==Integer.parseInt(one.get(i).getId()+"")){
                    list.add(twe.get(j).getTypeName());
                    k++;
                }
            }
            if(list.size()>0){
                stringList.add(list.toArray(new String[list.size()]));
                typeFatherArr.add(one.get(i).getTypeName());
            }
        }
        //将三级目录加入到对应的集合
        for (int i=0;i<twe.size();i++){
            int k = 0;
            List<String> list = new ArrayList<>();
            for (int j=0;j<three.size();j++){
                if(three.get(j).getPid()==Integer.parseInt(twe.get(i).getId()+"")){
                    list.add(three.get(j).getTypeName());
                    k++;
                }
            }
            if(list.size()>0){
                stringList.add(list.toArray(new String[list.size()]));
                typeFatherArr.add(twe.get(i).getTypeName());
            }
        }
        HashMap<String, String[]> areaMap = new HashMap<>();
        int oneSize = one.size();
        int tweSize = twe.size();
        int sizeLength = oneSize+tweSize;
        for (int i = 0;i<stringList.size();i++) {
            if(i<oneSize){
                areaMap.put(one.get(i).getTypeName(),stringList.get(i));
            }else if(i<sizeLength&&i>=oneSize){
                areaMap.put(twe.get(i-oneSize).getTypeName(),stringList.get(i));
            }
        }
        System.out.println("areaMap:"+areaMap.toString());
        //创建一个可隐藏的sheet页
        Sheet hideSheet = model.createSheet("area");
        //作用是隐藏sheet,未完成前注释掉用来查看信息导出是否正确
        //model.setSheetHidden(model.getSheetIndex(hideSheet),true);
        int rowId = 0;
        //第一行存省的信息
        Row typeRow = hideSheet.createRow(rowId++);
        typeRow.createCell(0).setCellValue("题目类型");
        for (int i=0;i<typeOneArr.length;i++){
            Cell cell = typeRow.createCell(i + 1);
            cell.setCellValue(typeOneArr[i]);
        }
        //将具体的数据写入到每一行中，行开头是父，后面是子
        String[] fatherArr = typeFatherArr.toArray(new String[typeFatherArr.size()]);
        for (int i=0;i<fatherArr.length;i++){
            String key = fatherArr[i];
            String[] son = areaMap.get(key);
            Row row = hideSheet.createRow(rowId++);
            row.createCell(0).setCellValue(key);
            for(int j=0;j<son.length;j++){
                Cell cell = row.createCell(j + 1);
                cell.setCellValue(son[j]);
            }
            //添加名称管理器
            String range = wirteExcelUtil.getRange(1, rowId, son.length);
            Name name = model.createName();
            name.setNameName(key);
            String formula = "area!"+range;
            name.setRefersToFormula(formula);
        }
        XSSFDataValidationHelper helper = new XSSFDataValidationHelper((XSSFSheet)subjectSheet);
        //一级规则
        DataValidationConstraint constraint = helper.createExplicitListConstraint(typeOneArr);
        // 四个参数分别是：起始行、终止行、起始列、终止列
        CellRangeAddressList cellRangeAddressList = new CellRangeAddressList(1, 100, 0, 0);
        DataValidation validation = helper.createValidation(constraint, cellRangeAddressList);
        validation.createErrorBox("error","请选择正确信息");
        validation.setShowErrorBox(true);
        validation.setSuppressDropDownArrow(true);
        for (int i=0;i<1;i++){
            Row row = hideSheet.createRow(rowId++);
            row.createCell(i).setCellValue("题目难度");
            for(int j=0;j<difficultyArr.length;j++){
                Cell cell = row.createCell(j + 1);
                cell.setCellValue(difficultyArr[j]);
            }
            //添加名称管理器
            String range = wirteExcelUtil.getRange(1, rowId, difficultyArr.length);
            Name name = model.createName();
            name.setNameName("题目难度");
            String formula = "area!"+range;
            name.setRefersToFormula(formula);
        }

        XSSFDataValidationHelper helpers = new XSSFDataValidationHelper((XSSFSheet)subjectSheet);
        //一级规则
        DataValidationConstraint constraints = helpers.createExplicitListConstraint(difficultyArr);
        // 四个参数分别是：起始行、终止行、起始列、终止列
        CellRangeAddressList cellRangeAddressLists = new CellRangeAddressList(1, 1000, 5, 5);
        DataValidation validations = helpers.createValidation(constraints, cellRangeAddressLists);
        //进行验证
        validations.createErrorBox("error","请选择正确信息");
        validations.setShowErrorBox(true);
        validations.setSuppressDropDownArrow(true);
        subjectSheet.addValidationData(validation);
        subjectSheet.addValidationData(validations);
        //对前1000行设置有效性
        for(int i=2;i<1000;i++){
            wirteExcelUtil.setDataValidation("A",subjectSheet,i,2);
            wirteExcelUtil.setDataValidation("B",subjectSheet,i,3);
        }
        FileOutputStream os =null;
        String filePath = "D:/subject.xlsx";
        try {
            os = new FileOutputStream(filePath);
            model.write(os);
            //进行题目上传
            String path = fastDFSClient.uploadFile(new File(filePath));
            System.out.println(path);
            return R.ok().put("path",path);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            IOUtils.closeQuietly(os);
        }
        return R.ok();
    }
}
